package com.chaoyi.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.chaoyi.dao.mysql.baidumv.ChannelMapper;
import com.chaoyi.dao.mysql.baidumv.OrderMapper;
import com.chaoyi.dao.mysql.stat.ChannelNewUserMapper;
import com.chaoyi.dao.redis.RedisPool;
import com.chaoyi.enums.DateType;
import com.chaoyi.enums.ShareType;
import com.chaoyi.util.NumUtil;
import com.chaoyi.vo.Channel;
import com.chaoyi.vo.NewUserCount;
import com.chaoyi.vo.OrderStat;

import redis.clients.jedis.Jedis;

@Service
public class OrderService {
	private final Logger logger = LoggerFactory.getLogger(OrderService.class);
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private ChannelMapper channelMapper;
	@Autowired
	private ChannelNewUserMapper channelNewUserMapper;
	@Autowired
	private SqlSessionTemplate sqlSessionTemplateBaiduMv;
	
	public void orderStat(String startTime,String endTime){
		removeChannelSum();
		logger.info("统计订单数据：startTime="+startTime+" endTime="+endTime);
		logger.info("统计订单数据：获取流水");
		List<OrderStat> totalPriceList = orderMapper.selectTotalPrice(startTime, endTime);
		List<OrderStat> deductionPrice = orderMapper.selectDeductionPrice(startTime, endTime);
		logger.info("统计订单数据：支付用户数");
		List<OrderStat> payUserCountList = orderMapper.selectPayUserCount(startTime, endTime);
		logger.info("统计订单数据：新增用户数");
		List<NewUserCount> newUserCountList = channelNewUserMapper.selectNewUserCount(startTime, endTime);
		Map<String,OrderStat> map = new HashMap<String,OrderStat>();
		for(OrderStat stat:totalPriceList){
			OrderStat current = map.get(stat.getChannelId());
			if(current==null){
				current = new OrderStat();
				current.setChannelId(stat.getChannelId());
				current.setCreateDate(stat.getCreateDate());
				map.put(current.getChannelId(), current);
			}
			current.setTotalPrice(current.getTotalPrice()+stat.getTotalPrice());
		}
		for(OrderStat stat:deductionPrice){
			OrderStat current = map.get(stat.getChannelId());
			if(current==null){
				current = new OrderStat();
				current.setChannelId(stat.getChannelId());
				current.setCreateDate(stat.getCreateDate());
				map.put(current.getChannelId(), current);
			}
			current.setChannelIncome(current.getChannelIncome()+stat.getChannelIncome());
		}
		for(OrderStat stat:payUserCountList){
			OrderStat current = map.get(stat.getChannelId());
			if(current==null){
				current = new OrderStat();
				current.setChannelId(stat.getChannelId());
				current.setCreateDate(stat.getCreateDate());
				map.put(current.getChannelId(), current);
			}
			current.setPayUserCount(current.getPayUserCount()+stat.getPayUserCount());
		}
		for(NewUserCount count:newUserCountList){
			OrderStat current = map.get(count.getChannelId());
			if(current==null){
				current = new OrderStat();
				current.setChannelId(count.getChannelId());
				current.setCreateDate(count.getCreateDate());
				map.put(current.getChannelId(), current);
			}
			current.setNewUserCount(current.getNewUserCount()+count.getNewUserCount());
		}
		List<Channel> channelList = channelMapper.getChannelList();
		Map<String,Channel> channelMap = new HashMap<String,Channel>();
		for(Channel channel:channelList ){
			channelMap.put(channel.getChannelId(), channel);
		}
		List<OrderStat> resultList = new ArrayList<OrderStat>(map.size());
		for(OrderStat stat:map.values()){
			Channel channel = channelMap.get(stat.getChannelId());
			if(channel==null){
				channel = new Channel();
			}
			stat.setDateType(channel.getDateType());
			stat.setShareType(channel.getShareType());
			stat.setDeduction(channel.getDeduction());
			stat.setShareRatio(channel.getShareRatio());
			stat.setPrice(channel.getPrice());
			stat.setCompanyId(channel.getCompanyId());
			if(stat.getDateType()==DateType.REAL_TIME.ordinal()&&stat.getShareType()==ShareType.CPS.ordinal()){	
				stat.setRealIncome((double)stat.getChannelIncome()*stat.getShareRatio()/100);
				if(channel.getShowHundred() ==0){
					stat.setChannelIncome(stat.getChannelIncome()*stat.getShareRatio()/100);
				}
			}else{
				stat.setChannelIncome(0);
				stat.setRealIncome(0);
			}
			if(stat.getNewUserCount() >= 100){
				stat.setNewUserCountDedu((int) (stat.getNewUserCount()*0.95));
			}else{
				stat.setNewUserCountDedu(stat.getNewUserCount());
			}
			resultList.add(stat);
		}
		logger.info("统计订单数据：插入订单统计表");
		SqlSession sqlSession = null;
		try {
			sqlSession = sqlSessionTemplateBaiduMv.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
			for(OrderStat vo:resultList){
				vo.setChannelIncome(NumUtil.mathFormat(vo.getChannelIncome()));
				sqlSession.insert("com.chaoyi.dao.mysql.baidumv.OrderStatMapper.insert",vo);
			}
			sqlSession.commit();
		} catch(Exception e){
			sqlSession.rollback();
			throw e;
		} finally{
			if(sqlSession!=null){
				sqlSession.clearCache();
				sqlSession.close();
			}
		}
	}
	//每日清空扣量（保证每天第一条不扣）
	public void removeChannelSum(){
		logger.info("开始清空扣量累加值");
		try (Jedis jedis = RedisPool.INSTANCE.getResource()) {
			List<Channel> channelList = channelMapper.getChannelList();
			for(Channel channel : channelList){
				jedis.set("channel:sum:"+channel.getChannelId(), "0");
			}
		}catch (Exception e) {
			logger.error("清空扣量失败",e);
		}
		logger.info("清空扣量累加值成功！");
	}
}
